package com.jt.controller;


import com.jt.annotation.RequiredLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@Slf4j
//@RefreshScope 假如属性的值来自配置中心，配置中心的值发生变化，方法会重新构建，属性的值也要发生变化
@RequestMapping("/resource")
public class ResourceController {
    @Value("${jt.resource.path}")
    private String resourcePath;
    @Value("${jt.resource.host}")
    private String resourceHost;

    //@PreAuthorize("hasAuthority('sys:res:add')")
    @PreAuthorize("hasAuthority('sys:res:create')")
    @RequiredLog("文件上传")
    @PostMapping("/upload/")
    public String uploadFile(MultipartFile uploadFile) throws IOException {
        String dateDir = DateTimeFormatter.ofPattern("yyyy/MM/dd")
                .format(LocalDate.now());
        File uploadFileDir = new File(resourcePath,dateDir);
        if (!uploadFileDir.exists()){
            uploadFileDir.mkdirs();
        }
        String originalFilename = uploadFile.getOriginalFilename();
        String ext = originalFilename.substring(
                originalFilename.lastIndexOf("."));
        String newFilePrefix = UUID.randomUUID().toString();
        String newFileName = newFilePrefix+ext;
        File file = new File(uploadFileDir,newFileName);
        uploadFile.transferTo(file);
        String fileRealPath = resourceHost+dateDir+"/"+newFileName;
        log.debug("fileRealPath {}",fileRealPath);
        return fileRealPath;

    }
}
